package com.db.person.controller;

import com.db.person.bean.UserVisit;
import com.db.person.bean.User_inf;
import com.db.person.service.IUserService;
import com.db.person.service.IUserVisitService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;

@Controller
public class UserLoginController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserVisitService userVisitService;

    @RequestMapping("/tologin")
    public String toLogin(){
        return "loginForm";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest req,String loginname, String password, String user_input_verifyCode, Model model, HttpSession session) throws UnknownHostException {

        //进行验证码的校验 user_input_verifyCode就是用户输入的验证码
        //从session中获取之前生成好的验证码
        String oldcode = session.getAttribute("code").toString();
        if(!user_input_verifyCode.equals(oldcode)){
            //直接返回 进行提示
            String str = "验证码错误";
            model.addAttribute("message",str);
            return "loginForm";
        }


        SimpleHash simpleHash = new SimpleHash("MD5",password,loginname,1024);
        String realPwd = simpleHash.toString();
        User_inf login = userService.login(loginname, realPwd);

        //1.mapper配置文件中 改成loginname
        //2.UserServiceImpl里面的login方法要完善   return userMapper.login(loginname,password);

        if(login==null){
            //失败 跳转到登录页面
            String str = "用户名密码错误";
            model.addAttribute("message",str);
            return "loginForm";
        }else{
            Integer statusId = login.getStatusId();//根据此字段判断用户是否授权了  1就是授权  2没有授权
            if(statusId==2){
                String str = "此用户还没有授权";
                model.addAttribute("message",str);
                return "loginForm";
            }
            //成功
            session.setAttribute("user_session",login);

            //往登录记录表插入一条数据
            InetAddress ip = Inet4Address.getLocalHost();
            String ip1 = ip.toString();
            String[] a = ip1.split("/");
            String ip2 = a[1];
            String agent=req.getHeader("user-agent");
            StringTokenizer st=new StringTokenizer(agent,";");
            st.nextToken();
            //得到用户的浏览器名
            String userbrowser=st.nextToken();
            //得到用户的操作系统名
            String useros=st.nextToken();
            String[] useros1=useros.split("/");
            String useros2 = useros1[1];
            String useros3 = useros1[2];

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
            String currentDateStr = df.format(new Date());

            UserVisit userVisit = new UserVisit();
            if(agent.indexOf("Android")!=-1) {
                userVisit.setUserFrom("移动端");
            }else if(agent.indexOf("iPhone") != -1 || agent.indexOf("iPad") != -1) {
                userVisit.setUserFrom("苹果端");
            }else {
                userVisit.setUserFrom("PC端");
            }
            userVisit.setLoginTime(currentDateStr);
            userVisit.setLoginname(loginname);
            userVisit.setVisitIp(ip2);
            userVisit.setBrowser(useros2);
            userVisit.setSystem(userbrowser);
            userVisit.setVersion(useros3);
            userVisit.setUserAddress("河南");//java可以得到经度和纬度

            InetAddress addr = null;
            String address = "";
            addr = InetAddress.getLocalHost();//新建一个InetAddress类
            address = addr.getHostName().toString();// 获得本机名称

            userVisit.setIphone(address);
            //把这条userVisit数据插入数据库
            userVisitService.insert(userVisit);
            //把主键存到session中，用户正常退出的时候取出 用来更新退出时间
            session.setAttribute("uid",userVisit.getId());

            return "index";
        }
    }

    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session){

        //1.维护用户访问信息记录表的退出字段
        Integer uid = (Integer) session.getAttribute("uid");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
        String currentDateStr = df.format(new Date());
        //根据id修改退出时间
        userVisitService.updateById(currentDateStr,uid);

        //2.清除session
        session.invalidate();

        return "loginForm";
    }

}
